//
//  UserAccount.swift
//  Weibo
//
//  Created by 张远文 on 16/4/26.
//  Copyright © 2016年 张远文. All rights reserved.
//

import UIKit

class UserAccount: NSObject,NSCoding {

    //属性
    //登录令牌
    var access_token: String?
    //登录令牌有效期,精确到秒数
    var expires_in: NSTimeInterval = 0 {
        
        didSet {
            expires_date = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    //登录令牌到期日期
    var expires_date: NSDate?
    //用户id
    var uid: String?
    //用户头像地址
    var avatar_large: String?
    //用户昵称
    var name: String?
    
    //归档和解档
    func saveAccount() {
      
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.plist")
        
        
        
        NSKeyedArchiver.archiveRootObject(self, toFile: path)
    }
    
    class func loadAccount() -> UserAccount? {
        
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.plist")
        
        if let userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? UserAccount {
        
            if userAccount.expires_date?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
                return userAccount
            }
        }
        return nil
    }
    
    //初始化方法
    //利用kvc方法
    init(dict: [String : AnyObject]) {
        
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    
    //协议方法
    required init?(coder aDecoder: NSCoder) {
        
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        uid = aDecoder.decodeObjectForKey("uid") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
        name = aDecoder.decodeObjectForKey("name") as? String
        expires_date = aDecoder.decodeObjectForKey("expires_date") as? NSDate
    }
    
    func encodeWithCoder(aCoder: NSCoder) {
        
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(expires_date, forKey: "expires_date")
    }
    
    override var description: String {
        
        let keys = ["access_token","expires_in","uid","avatar_large","name","expires_date"]
        
        return dictionaryWithValuesForKeys(keys).description
        
    }
    
}
